<template>
  <div ref="container"></div>
</template>

<script setup lang="ts">
import type { WeekServerCount } from '~/types';
import * as echarts from 'echarts';
const props = defineProps({
  data: {
    type: Array as PropType<WeekServerCount[]>,
    required: true
  }
});

const container = ref(null);
let myChart: any;

function initChart(data: WeekServerCount[]) {
  if (!myChart) {
    myChart = echarts.init(container.value);
  }
  const option = {
    xAxis: {
      type: 'category',
      data: data.map((d: WeekServerCount) => d.date?.substring(5)),
      axisLine: {
        lineStyle: {
          color: '#4768A9'
        }
      },
      axisLabel: {
        color: '#e6f7ffd9'
      },
      axisTick: {
        show: false
      }
    },
    grid: {
      top: 25,
      right: 20,
      bottom: 40,
      left: 50
    },
    yAxis: {
      axisLine: {
        lineStyle: {
          color: '#C9CDD4'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#19ECFF44',
          type: 'dashed'
        }
      },
      type: 'value'
    },
    series: [
      {
        type: 'line',
        symbol: 'circle',
        symbolSize: 10,
        itemStyle: {
          color: '#49FDFD',
          borderWidth: 10,
          borderColor: '#49FDFD44'
        },
        lineStyle: {
          width: 1,
          color: '#49FDFD'
        },
        smooth: true,
        data: data.map((d) => ({ name: d.date, value: d.dredge }))
      },
      {
        type: 'bar',
        data: data.map((d) => ({ name: d.date, value: d.usage })),
        barWidth: 12,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#18FAF5' },
            { offset: 1, color: '#003BB0' }
          ])
        }
      }
    ]
  };
  myChart.setOption(option);
}

watch(
  () => props.data,
  (val) => {
    if (val) {
      initChart(val);
    }
  }
);

onMounted(() => {
  if (props.data) {
    initChart(props.data);
  }
});
</script>
